package com.xiaoq.matrix.weixin.util;

import java.io.File;
import java.text.MessageFormat;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoq.coms.util.JsonUtil;
import com.xiaoq.coms.util.MapUtil;
import com.xiaoq.matrix.weixin.WXMassMsgResponse;
import com.xiaoq.web.DefaultMapper;

public class WeiXinUtil {
	
	private static final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
	private static final String URL_UPLOAD_IMAGE = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}";
	private static final String URL_ADD_MATERIAL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
	private static final String URL_ADD_NEWS = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}";
	private static final Logger LOG = LoggerFactory.getLogger(WeiXinUtil.class);
	private static final String URL_MASS_MSG = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";
	/**
	 * 发布微信文章里面图片url获取
	 * @param file
	 * @param accessToken
	 * @return
	 */
	public static String uploadImage(File file, String accessToken) {
		
			RestTemplate rest = new RestTemplate(); 
		    HttpHeaders headers = new HttpHeaders();
		    FileSystemResource resource = new FileSystemResource(file.getAbsolutePath());
		    MediaType mtype = MediaType.parseMediaType("multipart/form-data");
		    headers.setContentType(mtype);
		    String cd = "filename=\"" + file.getName() + "\"";
		    headers.add("Content-Disposition", cd);
		    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
		    param.add("media", resource);
		    HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(param, headers);
		    ResponseEntity<String> result  = rest.postForEntity(MessageFormat.format(URL_UPLOAD_IMAGE, accessToken), files, String.class);
		    String body = result.getBody();
		    ObjectMapper objectMapper = new DefaultMapper();
		    WeiXinImgUrlVo weixinImgVo = null;
		    String url = null;
		    try {
				weixinImgVo = objectMapper.readValue(body, WeiXinImgUrlVo.class);
				url = weixinImgVo.getUrl();
			} catch (Exception e) {
				LOG.error("微信图片支持解析出错", e);
			} 
		    return url;
		
	}
	
	/**
	 * 添加一个永久素材
	 * @param type
	 * @param file
	 * @param accessToken
	 * @return
	 */
	public static WeiXinMaterialVo addMaterial(String type,File file,String accessToken) {
			RestTemplate rest = new RestTemplate(); 
		    HttpHeaders headers = new HttpHeaders();
		    FileSystemResource resource = new FileSystemResource(file.getAbsolutePath());
		    MediaType mtype = MediaType.parseMediaType("multipart/form-data");
		    headers.setContentType(mtype);
		    String cd = "filename=\"" + file.getName() + "\"";
		    headers.add("Content-Disposition", cd);
		    MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
		    param.add("media", resource);
		    HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(param, headers);
		    ResponseEntity<String> result = rest.postForEntity(MessageFormat.format(URL_ADD_MATERIAL, accessToken, type), files, String.class);
		    String body = result.getBody();
		    ObjectMapper objectMapper = new DefaultMapper();
		    WeiXinMaterialVo weiXinMaterialVo = null;
		    try {
		    	weiXinMaterialVo = objectMapper.readValue(body, WeiXinMaterialVo.class);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
		    return weiXinMaterialVo;
	}
	
	/**
	 * 添加一个图文素材返回一个素材Id
	 * @param title
	 * @param thumbMediaId
	 * @param author
	 * @param digest
	 * @param showCoverPic
	 * @param content
	 * @param contentSrcUrl
	 * @param accessToken
	 * @return
	 */
	public static WeiXinMaterialVo addNews(String title,String thumbMediaId,String author,
						String digest,Integer showCoverPic,String content,
						String contentSrcUrl,String accessToken) {
	    RestTemplate rest = new RestTemplate();
	    
	    Map<String, Object> article = MapUtil.buildMapKVGen(new Object[][] {
	    	{"title", title},
	    	{"thumb_media_id", thumbMediaId},
	    	{"author", author},
	    	{"digest", digest},
	    	{"show_cover_pic", showCoverPic == null ? 0 : 1},
	    	{"content", content == null ? "" : content},
	    	{"content_source_url", contentSrcUrl == null ? "" : contentSrcUrl}
	    }, String.class, Object.class);
	    Map<String, Object> body = MapUtil.buildMapKVGen(new Object[][] {{"articles", new Object[] {article}}}, String.class, Object.class);
	    HttpHeaders headers = new HttpHeaders();  
	    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);  
		headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
		HttpEntity<String> reqEntity = new HttpEntity<String>(JsonUtil.asString(body), headers); 
	    String respStr = rest.postForObject(MessageFormat.format(URL_ADD_NEWS, accessToken), reqEntity, String.class);
	    LOG.info("微信添加一个图文素材返回结果"+respStr);
	    ObjectMapper objectMapper = new DefaultMapper();
	    WeiXinMaterialVo weiXinMaterialVo = null;
	    try {
	    	weiXinMaterialVo = objectMapper.readValue(respStr, WeiXinMaterialVo.class);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	    return weiXinMaterialVo;
	}
	
	/**
	 * 群发图文信息
	 * @param accessToken
	 * @param mediaId
	 * @return
	 */
	public static WXMassMsgResponse massMsgArticle(String accessToken,String mediaId) {
		RestTemplate rest = new RestTemplate();

		Map<String, String> news = MapUtil.buildMapKVGen(new String[][] { { "media_id", mediaId } }, String.class,
				String.class);

		Map<String, Object> filter = MapUtil.buildMapKVGen(new Object[][] { { "is_to_all", true } }, String.class,
				Object.class);

		Map<String, Object> body = MapUtil.buildMapKVGen(
				new Object[][] { { "filter", filter }, { "mpnews", news }, { "msgtype", "mpnews" } }, String.class,
				Object.class);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
		HttpEntity<String> reqEntity = new HttpEntity<String>(JsonUtil.asString(body), headers);
		WXMassMsgResponse resp = rest.postForObject(MessageFormat.format(URL_MASS_MSG, accessToken), reqEntity,
				WXMassMsgResponse.class);
		LOG.info("微信分发的结果："+JsonUtil.asString(resp));
		return resp;
	}
	
	public static String getToken(String appid,String secret) {
		RestTemplate rest = new RestTemplate();
		String respStr = rest.getForObject(MessageFormat.format(URL_ACCESS_TOKEN, appid, secret), String.class);
		ObjectMapper objectMapper = new DefaultMapper();
		WeiXinTokenVo weiXinTokenVo = null;
		try {
			weiXinTokenVo = objectMapper.readValue(respStr, WeiXinTokenVo.class);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		} 
		String token = weiXinTokenVo.getAccessToken();
		return token;
	}

}
